<template>
  <div v-loading="loading">
    <el-form
      v-if="false"
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="coalType">
        <el-select
          multiple
          clearable
          v-model="queryParams.coalType"
          placeholder="请选择"
          class="!w-300px"
        >
          <el-option
            v-for="dict in coalTypeList"
            :key="dict.id"
            :label="dict.coalName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button-group class="ml-4">
          <el-button
            v-for="item in dateTypeList"
            :type="dateType === item.value ? 'primary' : 'default'"
            @click="dateTypeChange(item.value)"
            :key="item.value"
            >{{ item.label }}</el-button
          >
        </el-button-group>
      </el-form-item>
      <el-form-item label="选择时间" prop="createTime">
        <DatePicker
          v-model="queryParams.createTime"
          :dateType="dateType"
          @dataChange="datePickerChange"
        ></DatePicker>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <section class="flex justify-between flex-wrap">
      <el-card
        v-for="item in cardList"
        class="h-120px mb-4 w-400px active-bg hover:bg-sky-50"
        :class="[item.className, { 'cursor-pointer': item.url }]"
        @click.stop="linkToPage(item.url)"
      >
        <div class="card-title">{{ item.titleName }}</div>
        <div class="card-content">
          <div v-for="data in item.resultData || []" class="space-y-1">
            <div class="text-label">{{ data.dataName }}</div>
            <div
              class="text-value"
              @click.stop="linkToPage(data?.url || item.url)"
              :class="{ 'cursor-pointer': data?.url }"
              >{{ data.dataValue }}</div
            >
          </div>
        </div>
      </el-card>
    </section>
    <el-container class="!grid grid-cols-2 gap-x-4">
      <el-card>
        <el-container class="flex">
          <Echart
            :width="300"
            :height="300"
            :options="funnelOptionData"
            @initReady="initFunnel"
            @click="linkToPage('/dataCenter/conversionRateAnalysis')"
          />
          <el-table
            :data="rateList"
            border
            stripe
            class="mt-40px funnel-table"
            :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
          >
            <el-table-column label="" align="center" width="80" fixed="left">
              <template #default="{ $index }">
                <div
                  :class="{
                    'bg-0ea5e9': $index === 0,
                    'bg-f59e0b': $index === 1,
                    'bg-ec4899': $index === 2,
                    'bg-8b5cf6': $index === 3
                  }"
                  class="h-10px my-12px"
                >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="名称"
              align="center"
              prop="name"
              min-width="100"
              fixed="left"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="人数" align="center" prop="peopleNumber" min-width="100" />
            <el-table-column label="转化率" align="center" prop="conversionRate" min-width="100">
              <template #default="{ row }">
                <el-progress
                  :text-inside="true"
                  :stroke-width="16"
                  :percentage="row.conversionRate"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="月环比增速"
              align="center"
              prop="monthGrowthRate"
              min-width="100"
            >
              <template #default="{ row }">
                <span
                  v-if="isEmpty(row.monthGrowthRate)"
                  :class="{
                    'text-teal-500': row.monthGrowthRate < 0,
                    'text-red-500': row.monthGrowthRate > 0
                  }"
                  >{{ row.monthGrowthRate.toFixed(2) }}%</span
                >
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
        </el-container>
      </el-card>
      <el-card>
        <Echart
          :height="300"
          :options="candlestickOptionData"
          @initReady="initCandlestick"
          @click="linkToPage('/dataCenter/premiumIndexAnalysis')"
        />
      </el-card>
    </el-container>
    <el-container class="!grid grid-cols-2 gap-x-4 mt-4">
      <el-card>
        <Echart
          :height="300"
          :options="barOptionData"
          @initReady="initBar"
          @click="linkToPage('/dataCenter/priceAnalysis')"
        />
      </el-card>
      <el-card>
        <div class="flex justify-between mb-5 items-center">
          <span class="font-bold">客户排名</span>
          <span
            @click="linkToPage('/dataCenter/customerRank')"
            class="flex items-center text-sm text-neutral-400 cursor-pointer hover:text-blue-400"
          >
            更多<el-icon>
              <DArrowRight />
            </el-icon>
          </span>
        </div>
        <el-table
          :data="list"
          border
          stripe
          height="255"
          :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
        >
          <el-table-column label="排名" align="center" width="63" fixed="left">
            <template #default="{ $index }">
              <div
                :class="{
                  rankOne: $index === 0,
                  rankTwo: $index === 1,
                  rankThree: $index === 2,
                  rankOther: $index > 2
                }"
                class="pt-1px"
              >
                {{ $index + 1 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="客户名称"
            align="center"
            prop="customerName"
            min-width="150"
            fixed="left"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="采购量(万吨)"
            align="center"
            prop="purchaseTotal"
            min-width="150"
          />
          <el-table-column
            label="总金额(万元)"
            align="center"
            prop="purchaseAmountTotal"
            min-width="150"
          />
          <el-table-column
            label="平均价格(元/吨)"
            align="center"
            prop="averagePrice"
            min-width="150"
          />
        </el-table>
      </el-card>
    </el-container>
  </div>
</template>
<script setup lang="ts" name="boardHome">
import * as dataCenter from '@/api/dataCenter'
import { EChartsOption } from 'echarts'
import { isEmpty, initMonthTimeRange, dateArrayJoin, isHasData } from '@/utils/common'
import { dateTypeList, cardUrlMap, dataStyleMap } from '../dataCenter.data'
import { funnelOption, candlestickOption, barOption } from '../echarts-data'
const loading = ref(true)
const list = ref([])
const rateList = ref([])
const queryFormRef = ref()
const router = useRouter()
const dateType = ref('month')
const barChart = ref()
const funnelChart = ref()
const candlestickChart = ref()
const cardList: Record<string, any> = ref([])
const funnelOptionData = reactive<EChartsOption>(funnelOption) as EChartsOption
const candlestickOptionData = reactive<EChartsOption>(candlestickOption) as EChartsOption
const barOptionData = reactive<EChartsOption>(barOption) as EChartsOption
const queryParams: Record<string, any> = ref({
  coalType: [],
  createTime: []
})
const coalTypeList: Record<string, any> = ref([])
let timer: any = null
let timeTange: any[] = []

/** 搜索按钮操作 */
const handleQuery = () => {
  getHomePageReport()
}

/** 重置按钮操作 */
const resetQuery = () => {
  timeTange = []
  dateType.value = 'month'
  queryFormRef.value.resetFields()
  handleQuery()
}

const dateTypeChange = (type) => {
  dateType.value = type
  queryParams.value.createTime = []
}

const linkToPage = (url) => {
  if (!url) return
  router.push({ path: url })
}

const initFunnel = (chart) => {
  funnelChart.value = chart
}

const initCandlestick = (chart) => {
  candlestickChart.value = chart
}

const initBar = (chart) => {
  barChart.value = chart
}

const datePickerChange = ($event) => {
  timeTange = $event
}

const getHomePageReport = async () => {
  const res = await dataCenter.getHomePageReport({})
  cardList.value = handleCardList(res || [])
}

const handleCardList = (list) => {
  return list.map((e) => {
    if (typeof cardUrlMap?.[e?.className] === 'string') {
      e.url = cardUrlMap[e.className]
    } else {
      e.resultData = e.resultData.map((m) => {
        if (typeof cardUrlMap?.[e?.className] === 'object') {
          m.url = cardUrlMap[e.className]?.[m?.dataName]
        }
        return m
      })
    }
    return e
  })
}

const getConversionStatistics = async () => {
  const res = await dataCenter.getConversionStatistics({
    timePeriod: 'month',
    localDates: timeTange
  })
  rateList.value = (res?.conversionBaseRespVOS || []).filter((e) => e.name !== '查看人数')
  initFunnelData(res?.dataRespVOList || [])
}

const initFunnelData = (list) => {
  funnelChart.value.setOption({
    title: {
      text: '转化率分析'
    },
    series: [
      {
        name: '转化率分析',
        sort: 'none',
        left: '10%',
        data:
          list
            ?.filter((m) => m.dataName !== '查看人数')
            ?.map((e) => {
              return {
                max: getMaxValue(list),
                name: e.dataName,
                value: e.value + 10,
                itemStyle: dataStyleMap[e.dataName],
                label: {
                  formatter: (param) => {
                    return param.value - 10
                  }
                }
              }
            }) || []
      }
    ]
  })
}

const getMaxValue = (list) => {
  if (!list.length) {
    return 0
  }
  return Math.max(...list.map((e) => e.value))
}

const getPremiumIndex = async () => {
  const res = await dataCenter.getPremiumIndex({})
  initCandlestickData(res)
}

const initCandlestickData = (data) => {
  const dateList =
    data.localDateList?.map((e) => {
      return dateArrayJoin(e)
    }) || []
  const dataList = data.priceDataList || []
  toRaw(candlestickChart.value).setOption({
    title: {
      text: '溢价指数分析'
    },
    grid: {
      right: 20,
      bottom: 30
    },
    tooltip: {
      formatter: (params) => {
        const data = params[0].data
        return (
          params[0].name +
          '<br>' +
          '开始价格:' +
          data[1] +
          '(元/吨)<br>' +
          '结束价格:' +
          data[2] +
          '(元/吨)<br>' +
          '最低溢价:' +
          data[3] +
          '(元/吨)<br>' +
          '最高溢价:' +
          data[4] +
          '(元/吨)'
        )
      }
    },
    xAxis: {
      data: dateList
    },
    series: [
      {
        data: dataList
      }
    ],
    dataZoom: [
      {
        show: false,
        start: 0,
        end: 100
      }
    ]
  })
}

const getPricedStatisticsChart = async () => {
  const res = await dataCenter.getPricedStatisticsChart({
    timePeriod: 'month',
    tradingDate: timeTange.join(',')
  })
  initBarData(res)
}

const initBarData = (data) => {
  barChart.value.setOption({
    title: {
      text: '价格分析'
    },
    grid: {
      right: 20,
      bottom: 30
    },
    xAxis: {
      data: data.date || []
    },
    series: getSeriesData(data.columnChartMap),
    dataZoom: [
      {
        show: false,
        type: 'slider',
        start: 0,
        end: 100
      }
    ]
  })
}

const getLegendData = (data) => {
  if (isHasData(data)) {
    return []
  }
  return Object.keys(data)
}

const getSeriesData = (data) => {
  if (isHasData(data)) {
    return []
  }
  return getLegendData(data).map((key) => {
    return {
      name: key,
      type: 'bar',
      stack: '总量',
      barMaxWidth: 30,
      data: data[key]
    }
  })
}

const getCustomerPageByRank = async () => {
  const data = await dataCenter.getCustomerPageByRank({})
  const result = data?.customerStatisticsRankRespVOS || []
  if (data?.customerStatisticsRankRespVOS?.length <= 10) {
    list.value = result
  } else {
    list.value = result.slice(0, 10)
  }
}

const getHomeData = () => {
  loading.value = true
  try {
    timeTange = initMonthTimeRange()
    getHomePageReport()
    getConversionStatistics()
    getPremiumIndex()
    getPricedStatisticsChart()
    getCustomerPageByRank()
  } finally {
    timer = setTimeout(() => {
      loading.value = false
    }, 500)
  }
}

const bidCoalManageList = async () => {
  const res = await dataCenter.bidCoalManageList()
  coalTypeList.value = res || []
}

/** 初始化 **/
onMounted(() => {
  bidCoalManageList()
  getHomeData()
})

onBeforeUnmount(() => {
  if (timer) clearInterval(timer)
  window.removeEventListener('click', funnelChart.value)
  window.removeEventListener('dataZoom', candlestickChart.value)
})
</script>
<style lang="scss" scoped>
.bg-0ea5e9 {
  background-color: #0ea5e9;
}

.bg-10b981 {
  background-color: #10b981;
}

.bg-f59e0b {
  background-color: #f59e0b;
}

.bg-ec4899 {
  background-color: #ec4899;
}

.bg-8b5cf6 {
  background-color: #8b5cf6;
}

.rankOne {
  background-image: url('@/assets/imgs/dataCenter/rank-1.png');
}

.rankTwo {
  background-image: url('@/assets/imgs/dataCenter/rank-2.png');
}

.rankThree {
  background-image: url('@/assets/imgs/dataCenter/rank-3.png');
}

.rankOther {
  background-image: url('@/assets/imgs/dataCenter/rank-other.png');
}

.text-label {
  font-size: 14px;
  color: #666666;
}

.text-value {
  font-size: 18px;
  font-weight: bold;
}

.subject {
  background-image: url('@/assets/imgs/dataCenter/card-1.png');
}

.performance {
  background-image: url('@/assets/imgs/dataCenter/card-2.png');
}

.approval {
  background-image: url('@/assets/imgs/dataCenter/card-3.png');
}

.account {
  background-image: url('@/assets/imgs/dataCenter/card-4.png');
}

.card-title {
  @apply font-bold text-lg;
  height: 16px;
  line-height: 16px;
  padding-left: 8px;
  border-left: 3px solid #409efe;
}

.card-content {
  @apply flex mt-4;
}

.el-card:not(.approval) .card-content {
  > :nth-child(1) {
    width: calc(2 * (100% / 7));
  }

  > :nth-child(2) {
    width: calc(3 * (100% / 7));
    border-left: 1px solid #d9d9d9;
    text-align: center;
  }

  > :nth-child(3) {
    width: calc(2 * (100% / 7));
    border-left: 1px solid #d9d9d9;
    text-align: end;
  }
}

.el-card.approval .card-content {
  > :nth-child(1) {
    width: calc(100% / 4);
  }

  > :nth-child(2) {
    width: calc(100% / 4);
    border-left: 1px solid #d9d9d9;
    text-align: center;
  }

  > :nth-child(3) {
    width: calc(100% / 4);
    border-left: 1px solid #d9d9d9;
    text-align: center;
  }

  > :nth-child(4) {
    width: calc(100% / 4);
    border-left: 1px solid #d9d9d9;
    text-align: end;
  }
}

:deep(.el-card) {
  overflow: inherit !important;
}

:deep(.el-progress-bar__inner) {
  text-align: left !important;
}
</style>
